/**
 * 用户相关服务
 */
const util = require('../utils/util.js');
const api = require('../config/api.js');


function getAddressList() {
  let c = wx.getStorageSync('userAddress')
  if (c !== '') {
    return JSON.parse(c)
  } else {
    return []
  }

}

function delAddress(address) {
  let addressList = getAddressList().filter(x => x.id !== address.id)

  wx.setStorageSync('userAddress', JSON.stringify(addressList))
}

function addAddress(address) {
  let addressList = getAddressList()
  if (addressList.length == 0) {
    address.status = true
  }
  addressList.push(address)
  wx.setStorageSync('userAddress', JSON.stringify(addressList))

}

function delAddressById(addressId){
  let addressList = getAddressList()
  let addr = addressList.filter(x => x.id === addressId)[0]
  addressList = addressList.filter(x=> x.id !== addressId)
  if(addr.status === true && addressList.length>=1){
    addressList[0].status = true
  }
  wx.setStorageSync('userAddress', JSON.stringify(addressList))
}

function updateAdress(address) {
  let addressList = getAddressList()

  if (address.status == true) {
    addressList.forEach(x => x.status = false)
  }

  addressList = addressList.filter(x => x.id !== address.id)

  addressList.push(address)
  wx.setStorageSync('userAddress', JSON.stringify(addressList))
}

module.exports = {

  getAddressList,
  delAddress,
  updateAdress,
  addAddress,
  delAddressById

};